package com.autonavi.abs.generator.core.db;

import com.alibaba.druid.pool.DruidDataSource;
import com.autonavi.abs.generator.common.enumeration.DbTypeEnum;
import com.autonavi.abs.generator.common.model.ColumnMeta;
import com.autonavi.abs.generator.common.model.TableMeta;
import com.autonavi.abs.generator.core.property.AdbProperty;
import com.autonavi.abs.generator.core.property.DruidProperty;
import com.autonavi.abs.generator.util.DbUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author wwy
 * @version V1.0
 * <p>Description: adb DataSource</p>
 * @date 2020-08-10 18:37
 */
@Component
public class AdbMetaDataSource implements MetaDataSource {

    @Autowired
    private DruidProperty druidProperty;
    @Autowired
    private AdbProperty adbProperty;

    private DataSource dataSource;

    private String type = DbTypeEnum.Adb.getType();

    @Override
    public String getType() {
        return type;
    }

    @Override
    @PostConstruct
    public void initDataSource() {

        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(adbProperty.getDriverClass());
        ds.setUrl(adbProperty.getUrl());
        ds.setUsername(adbProperty.getUserName());
        ds.setPassword(adbProperty.getPassword());

        ds.setInitialSize(druidProperty.getInitialSize());
        ds.setMaxActive(druidProperty.getMaxActive());
        ds.setMinIdle(druidProperty.getMinIdle());
        ds.setMaxWait(druidProperty.getMaxWait());
        ds.setValidationQuery("SELECT 1");
        ds.setTestOnBorrow(druidProperty.isTestOnBorrow());

        this.dataSource = ds;
    }

    @Override
    public DataSource getDataSource() {
        if (dataSource == null) {
            initDataSource();
        }
        return dataSource;
    }

    @Override
    public Connection getConnection() throws SQLException {
        DataSource ds = getDataSource();
        Connection connection = ds.getConnection();
        return connection;
    }

    @Override
    public List<ColumnMeta> getColumnList(String tableName) throws Exception {
        Connection connection = getConnection();
        List<ColumnMeta> columnList = DbUtil.getColumnList(connection, tableName);
        return columnList;
    }

    @Override
    public List<TableMeta> getTableList() throws Exception {
        Connection connection = getConnection();
        List<TableMeta> tableList = DbUtil.getTableList(connection);
        return tableList;
    }
}
